<!--
  * 门店管理
  *
-->
<template>
  <a-card size="small" :bordered="false" :hoverable="true" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <!---------- 查询表单form begin ----------->
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="4">
          <a-form-item label="门店名称" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.store_name" placeholder="门店" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="联系人" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.contacts" placeholder="联系人" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="联系电话" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.phone" placeholder="联系电话" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="门店类型" class="smart-margin-bottom0">
            <Select name="Level" v-model:value="queryForm.store_level_id" placeholder="门店类型" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="refreshTable" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="6">
            <a-form-item label="启用状态" class="smart-margin-bottom0">
              <a-radio-group v-model:value="queryForm.status" @change="onSearch">
                <a-radio-button value="">全部</a-radio-button>
                <a-radio-button value="1">启用</a-radio-button>
                <a-radio-button value="2">禁用</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>

  <!---------- 查询表单form end ----------->
  <!---------- 表格操作行 begin ----------->
  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="add()" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="deleteData(selectedRowKeyList)" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'goods:batchDelete'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>

        <a-button @click="toMap()" type="primary" v-privilege="'goods:add'"> 门店地图 </a-button>

        <a-button @click="showImportModal" primary v-privilege="'goods:importGoods'">
          <template #icon>
            <ImportOutlined />
          </template>
          导入
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'store_name'">
            <a @click="detail(record)">{{ text }}</a>
          </template>
          <template v-if="column.dataIndex === 'salesman'">
            <span>{{ text && text.length > 0 ? text.map((e) => e.rename).join(',') : '' }}</span>
          </template>
          <template v-if="column.dataIndex === 'dealer'">
            <span>{{ text && text.length > 0 ? text.map((e) => e.name).join(',') : '' }}</span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-switch @click="modifyAction($event, record)" :loading="checkLoading" :checked="record.status == 1 ? true : false" checked-children="启用" un-checked-children="禁用" />
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-privilege="'goods:update'">详情</a-button>
              <a-button @click="add(record)" type="link" v-privilege="'goods:update'">编辑</a-button>
              <a-button @click="deleteData(record.id, record.store_name)" danger type="link" v-privilege="'goods:delete'">删除</a-button>
              <a-button @click="rechargeData(record.id)" type="link" v-privilege="'goods:delete'">充值</a-button>
              <a-button @click="boardDetail(record)" danger type="link" v-privilege="'goods:delete'">看板</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
  </a-card>
  <ShopFormModal ref="formModal" @reloadList="queryData" />

  <ImportModal ref="importModalRef" @downloadExcel="storeApi.exportTpl" :import-excel="storeApi.importXlsx" @reloadList="queryData" />
  <ShopDetailsModal ref="detailRef" />
  <ShopRechargeModal ref="rechargeRef" @reloadList="queryData" />
  <BoardDetailsModal ref="boardDetailRef" />
</template>
<script setup lang="ts">
import ShopRechargeModal from './components/shop-recharge-modal.vue'
import ShopFormModal from './components/shop-form-modal.vue'
import ShopDetailsModal from './components/shop-details-modal.vue'
import BoardDetailsModal from './const/board-details-modal.vue'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { storeApi } from '@/api/business/data/store-api'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { errorSentry } from '@/lib/error-sentry'
import Select from '@/components/business/select/index.vue'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import ImportModal from '@/components/support/import-modal/index.vue'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/data/store/store-event-name'
import EnumSelect from '@/components/framework/enum-select/index.vue'
const appConfigStore = useAppConfigStore()
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()
// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '门店',
    dataIndex: 'store_name'
    // width: 200
  },
  {
    title: '联系人',
    dataIndex: 'contacts',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'phone'
  },
  {
    title: '账户余额',
    dataIndex: 'account_sum',
    width: 100
  },
  {
    title: '所属片区',
    dataIndex: ['region', 'name'],
    width: 100
  },
  {
    title: '门店类型',
    dataIndex: ['level', 'level_name'],
    width: 100
  },
  {
    title: '启用状态',
    dataIndex: 'status'
  },
  {
    title: '地址',
    dataIndex: 'address'
  },
  {
    title: '录入时间',
    dataIndex: 'create_time'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 120 : 240
  }
])
// ---------------------------- 门店地图 ----------------------------
const { push } = useRouter()
const toMap = async () => {
  push({ path: '/data/map' })
}
// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const res = await storeApi.queryStoreList(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await storeApi.delStore({ id })
    return !!res
  },
  queryFormFilter: {
    store_name: '',
    contacts: '',
    phone: '',
    status: '',
    store_region_id: undefined,
    store_level_id: undefined
  },
  queryFormOp: {
    store_name: QUERY_FORM_OP['模糊查询'],
    contacts: QUERY_FORM_OP['模糊查询'],
    phone: QUERY_FORM_OP['模糊查询'],
    status: QUERY_FORM_OP['全等查询'],
    store_region_id: QUERY_FORM_OP['全等查询'],
    store_level_id: QUERY_FORM_OP['全等查询']
  }
})
eventEmitter.on(customEventName.QueryStoreList, (params) => {
  params.store_region_id = params.store_region_id == 0 ? '' : params.store_region_id
  setQuery(params, true)
  queryData()
})
function refreshTable() {
  eventEmitter.emit(customEventName.RefreshAreaList)
  resetQuery()
  eventEmitter.emit(customEventName.QueryStoreList, {
    page: 1,
    store_region_id: '' // 触发查询
  })
}
onMounted(queryData)
// 选择表格行
const selectedRowKeyList = ref<number[]>([])

function onSelectChange(selectedRowKeys: number[]) {
  selectedRowKeyList.value = selectedRowKeys
}
// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()
function add(goodsData) {
  formModal.value.showDrawer(goodsData)
}
// ---------------------------- 详情 ----------------------------
const detailRef = ref()
const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}

// ---------------------------- 看板 ----------------------------
const boardDetailRef = ref()
const boardDetail = (goodsData) => {
  boardDetailRef.value.showDrawer(goodsData)
}

// ---------------------------- 充值 ----------------------------
const rechargeRef = ref()
const rechargeData = (goodsData) => {
  rechargeRef.value.showModal(goodsData)
}

// ---------------------------- 修改状态 ----------------------------
const checkLoading = ref(false)
const modifyAction = async (checked, record) => {
  try {
    checkLoading.value = true
    const res = await storeApi.modifyStore({
      id: record.id,
      field: 'status',
      value: checked == true ? 1 : 2
    })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    checkLoading.value = false
  }
}

// ------------------------------- 导出和导入 ---------------------------------
const importModalRef = ref()
function showImportModal() {
  importModalRef.value.showImportModal()
}

// 导出
function onExport() {
  const filter = {
    store_name: queryForm.value.store_name,
    contacts: queryForm.value.contacts,
    phone: queryForm.value.phone,
    status: queryForm.value.status,
    store_region_id: queryForm.value.store_region_id,
    store_level_id: queryForm.value.store_level_id,
    payment_type: queryForm.value.payment_type
  }
  const op = {
    store_name: QUERY_FORM_OP['模糊查询'],
    contacts: QUERY_FORM_OP['模糊查询'],
    phone: QUERY_FORM_OP['模糊查询'],
    status: QUERY_FORM_OP['全等查询'],
    store_region_id: QUERY_FORM_OP['全等查询'],
    store_level_id: QUERY_FORM_OP['全等查询'],
    payment_type: QUERY_FORM_OP['全等查询']
  }
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(op)
  }
  storeApi.exportXlsx(data)
}
</script>
